package com.lanvideo.dao;

import com.lanvideo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户数据访问层
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据用户名查找用户
     */
    public User findByUsername(String username) {
        String sql = "SELECT id, username, password, name, role, status, email, phone, create_time, last_login_time FROM user WHERE username = ?";
        List<User> users = jdbcTemplate.query(sql, (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setName(rs.getString("name"));
            user.setRole(rs.getInt("role"));
            user.setStatus(rs.getInt("status"));
            user.setEmail(rs.getString("email"));
            user.setPhone(rs.getString("phone"));
            if (rs.getTimestamp("create_time") != null) {
                user.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
            }
            if (rs.getTimestamp("last_login_time") != null) {
                user.setLastLoginTime(rs.getTimestamp("last_login_time").toLocalDateTime());
            }
            return user;
        }, username);
        return users.isEmpty() ? null : users.get(0);
    }

    /**
     * 根据ID查找用户
     */
    public User findById(Integer id) {
        String sql = "SELECT id, username, password, name, role, status, email, phone, create_time, last_login_time FROM user WHERE id = ?";
        List<User> users = jdbcTemplate.query(sql, (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setName(rs.getString("name"));
            user.setRole(rs.getInt("role"));
            user.setStatus(rs.getInt("status"));
            user.setEmail(rs.getString("email"));
            user.setPhone(rs.getString("phone"));
            if (rs.getTimestamp("create_time") != null) {
                user.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
            }
            if (rs.getTimestamp("last_login_time") != null) {
                user.setLastLoginTime(rs.getTimestamp("last_login_time").toLocalDateTime());
            }
            return user;
        }, id);
        return users.isEmpty() ? null : users.get(0);
    }

    /**
     * 保存用户
     */
    public int save(User user) {
        String sql = "INSERT INTO user (username, password, name, role) VALUES (?, ?, ?, ?)";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), 
                user.getName(), user.getRole());
    }

    /**
     * 更新用户信息
     */
    public int update(User user) {
        String sql = "UPDATE user SET name = ?, password = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getName(), user.getPassword(), user.getId());
    }

    /**
     * 检查用户名是否存在
     */
    public boolean existsByUsername(String username) {
        String sql = "SELECT COUNT(*) FROM user WHERE username = ?";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class, username);
        return count != null && count > 0;
    }

    /**
     * 获取所有用户
     */
    public List<User> findAll() {
        String sql = "SELECT * FROM user ORDER BY create_time DESC";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
    }

    /**
     * 根据角色获取用户列表
     */
    public List<User> findByRole(Integer role) {
        String sql = "SELECT * FROM user WHERE role = ? ORDER BY create_time DESC";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), role);
    }

    /**
     * 根据用户名查找用户（兼容方法）
     */
    public User findByName(String name) {
        String sql = "SELECT * FROM user WHERE name = ?";
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), name);
        return users.isEmpty() ? null : users.get(0);
    }

    /**
     * 根据邮箱查找用户
     */
    public User findByEmail(String email) {
        String sql = "SELECT * FROM user WHERE email = ?";
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), email);
        return users.isEmpty() ? null : users.get(0);
    }

    /**
     * 更新用户最后登录时间
     */
    public int updateLastLoginTime(Integer userId) {
        String sql = "UPDATE user SET last_login_time = NOW() WHERE id = ?";
        return jdbcTemplate.update(sql, userId);
    }

    /**
     * 创建用户（管理员功能）
     */
    public int createUser(User user) {
        String sql = "INSERT INTO user (username, name, email, phone, password, role, status, create_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP)";
        return jdbcTemplate.update(sql, user.getUsername(), user.getName(), user.getEmail(), 
                user.getPhone(), user.getPassword(), user.getRole());
    }

    /**
     * 更新用户（管理员功能）
     */
    public int updateUser(User user) {
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            String sql = "UPDATE user SET name = ?, email = ?, phone = ?, password = ?, role = ? WHERE id = ?";
            return jdbcTemplate.update(sql, user.getName(), user.getEmail(), user.getPhone(),
                    user.getPassword(), user.getRole(), user.getId());
        } else {
            String sql = "UPDATE user SET name = ?, email = ?, phone = ?, role = ? WHERE id = ?";
            return jdbcTemplate.update(sql, user.getName(), user.getEmail(), user.getPhone(),
                    user.getRole(), user.getId());
        }
    }

    /**
     * 删除用户（管理员功能）
     */
    public int deleteUser(Integer userId) {
        String sql = "DELETE FROM user WHERE id = ?";
        return jdbcTemplate.update(sql, userId);
    }

    /**
     * 更新用户密码（管理员功能）
     */
    public int updatePassword(Integer userId, String password) {
        String sql = "UPDATE user SET password = ? WHERE id = ?";
        return jdbcTemplate.update(sql, password, userId);
    }

    /**
     * 更新用户状态
     */
    public int updateUserStatus(Integer userId, Integer status) {
        String sql = "UPDATE user SET status = ? WHERE id = ?";
        return jdbcTemplate.update(sql, status, userId);
    }

    /**
     * 更新用户信息（可选包含密码）
     */
    public int updateUserInfo(User user) {
        // 处理空值，确保不会因为null值导致更新失败
        String username = user.getUsername() != null ? user.getUsername() : "";
        String name = user.getName() != null ? user.getName() : "";
        String email = user.getEmail() != null ? user.getEmail() : "";
        String phone = user.getPhone() != null ? user.getPhone() : "";
        Integer role = user.getRole() != null ? user.getRole() : 2; // 默认为学生角色
        
        String sql;
        Object[] params;
        
        // 如果提供了密码，则包含密码更新
        if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
            sql = "UPDATE user SET username = ?, name = ?, email = ?, phone = ?, role = ?, password = ? WHERE id = ?";
            params = new Object[]{username, name, email, phone, role, user.getPassword(), user.getId()};
            System.out.println("Updating user with password");
        } else {
            sql = "UPDATE user SET username = ?, name = ?, email = ?, phone = ?, role = ? WHERE id = ?";
            params = new Object[]{username, name, email, phone, role, user.getId()};
            System.out.println("Updating user without password");
        }
        
        // 调试日志
        System.out.println("=== UserDao.updateUserInfo Debug ===");
        System.out.println("SQL: " + sql);
        System.out.println("User ID: " + user.getId());
        System.out.println("Username: " + username);
        System.out.println("Name: " + name);
        System.out.println("Email: " + email);
        System.out.println("Phone: " + phone);
        System.out.println("Role: " + role);
        System.out.println("Password provided: " + (user.getPassword() != null && !user.getPassword().trim().isEmpty()));
        System.out.println("=== End Debug ===");
        
        try {
            // 先检查用户是否存在
            String checkSql = "SELECT COUNT(*) FROM user WHERE id = ?";
            Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, user.getId());
            System.out.println("User exists check: " + count + " rows found for ID " + user.getId());
            
            if (count == null || count == 0) {
                System.out.println("User with ID " + user.getId() + " does not exist!");
                return 0;
            }
            
            int result = jdbcTemplate.update(sql, params);
            System.out.println("Update result: " + result);
            return result;
        } catch (Exception e) {
            System.out.println("Update error: " + e.getMessage());
            e.printStackTrace();
            return 0;
        }
    }
}
